import React, { Component } from 'react';
import styles from './index.module.less';
import UploadModal, { getFileName, fileVerif } from '../../components/UploadModal';
import PickerModal from '../../components/UploadModal/PickerModal';
import { Spin, message } from 'antd';
import isSuccess from '../../utils/error';
import taskServer from '../../services/task';
import projectServer from '../../services/project';
import { observer, inject } from 'mobx-react';
// 拖入上传文件

@inject(({ taskState, projectState }) => ({ taskState, projectState }))
@observer
class DragView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showMock: false,
      pickerShow: false,
      files: [],
      loading: false,
      loadText: '',
      showModalData: null,
    };
  }
  componentDidMount() {
    var contentDom = document.querySelector('#DragContent');

    //阻止相关事件默认行为
    contentDom.ondragcenter = () => {
      console.log('-------------------ondragcenter---------------');
      return false;
    };
    contentDom.ondragover = () => {
      console.log('-------------------ondragover---------------');
      this.setState({ showMock: true });
      setTimeout(() => {
        if (!this.state.showMock) {
          this.setState({ showMock: false });
        }
      }, 500);
      return false;
    };
    contentDom.ondragleave = () => {
      console.log('-------------------ondragleave---------------');
      this.state.showMock = false;
      return false;
    };

    //对拖动释放事件进行处理
    contentDom.ondrop = (e) => {
      var files = [];
      const data = e.dataTransfer.files;
      console.log(e, data);
      for (let i = 0; data.length > i; i++) {
        const val = fileVerif(data[i].name);
        if (!val) {
          message.warning('部分文件的格式超出平台上传范围，已为您剔除');
          continue
        }
        files.push({
          fileTarget: data[i],
          nameValue: data[i].name.split('.')[0],
          signValue: '',
          stampValue: '',
          remarkValue: '',
          dateValue: '',
          originValue: '',
          pageValue: '',
          partValue: '',
        });
      }
      if (files.length < 1) {
        this.setState({ showMock: false });
        return;
      }
      console.log(files);
      if(window.chattype === 1){
        this.setState({
          showMock: false,
          pickerShow: false,
          showModalData: {
            files: files,
            folderName: null,
            type: "2",
            stagename: null,
            recname: null,
          },
        });
      }else{
        this.props.taskState.clearDetail(); // 清除任务信息  避免从任务窗口切换到项目窗口时  有任务信息残留导致不能弹出项目信息面板
        
        this.setState({ files: files, showMock: false, pickerShow: true });
      }
      
      
    };
  }
  onPathValueChange = (val) => {
    console.log('onPathValueChange', val);
    const { files } = this.state;
    console.log('files--', files);
    try {
      const newFiles = files.map((item, index) => {
        return { ...item, ...val };
      });
      console.log('newFiles:', newFiles);
      this.setState({
        pickerShow: false,
        showModalData: {
          files: newFiles,
          folderName: val?.folder?.foldername,
          type: val.type,
          stagename: val.stage?.stagename,
          recname: val.project?.recname,
        },
      }); // 使用上传组件
    } catch (error) {
      console.log('err', error);
      message.warning('上传失败！请重新选择文件');
      this.setState({ pickerShow: false });
    }
  };
  onUploadResult = (res, callback) => {
    console.log('------------------onUploadResult-------------------', res);
    if (res && callback) {
      const { type } = this.state.showModalData;
      if (type == 1) {
        // 项目
        const { projectid, projecttype, stages } = this.props?.projectState.detailData || {};
        console.log('-------------stages-----------------');
        console.log(stages);
        this.props.projectState.getDetail({ projectid, stageid: stages?.[0]?.stageid }, true);
      } else if (type == 2) {
        // 任务
        const { info } = this.props?.taskState.detailData || {};
        !!info?.recid && this.props.taskState.getDetail({ taskid: info.recid }, true);
      }
      callback();
    } else {
    }
  };
  hidePickerModal = (val) => {
    console.log('hidePickerModal', val);
    this.setState({ pickerShow: false });
  };
  handleOk = async () => {
    const { files } = this.state;
    if (!files.length) {
      message.warning('请选择要上传的文件');
      return;
    }
    this.setState({ loading: true, loadText: '上传中...' });

    // 先上传文件
    const formData = new window.FormData();
    files.forEach((f) => formData.append('file', f.fileTarget, f.fileTarget.name));
    const res = await taskServer.uploadFiles(formData);
    this.setState({ loading: false });
    if (isSuccess(res)) {
      console.log('---uploadFiles---', res);
      this.handleSort(files, res);
    }
  };
  handleSort = async (files, res) => {
    // 分类处理
    // 1. 不同类型：上传到文件夹和上传到任务
    // 2. 同样类型但是不同文件之间和不同任务之间
    this.setState({ loading: true, loadText: '正在保存中...' });
    const toProjectObj = {};
    const innerProjectObj = {};
    const toTaskObj = {};
    files.forEach((f, i) => {
      const { filename, sourcefilename } = getFileName({
        ...f,
        response: res[i],
      });
      const type = f.type;
      if (type === '1') {
        // 上传到文件夹
        // 已项目id为基准分类
        const key = f.project.recid;
        if (toProjectObj[key]) {
          const newFiles = toProjectObj[key].files;
          if (!newFiles.includes(f.folder.folderid)) {
            // 判断文件夹id是否重复
            newFiles.push(f.folder.folderid);
            toProjectObj[key].files = newFiles;
          }
        } else {
          toProjectObj[key] = {
            projectid: key,
            stageid: f.stage.stageid,
            files: [f.folder.folderid],
          };
        }

        // 已文件夹id为基准分类
        const innerKey = f.folder.folderid;
        if (innerProjectObj[innerKey]) {
          const newItems = innerProjectObj[innerKey].items;
          newItems.push({
            filename,
            sourcefilename,
            // filetype: 1,
            folderid: f.folder.folderid,
            uploadfileid: res[i].fileid,
            extension: res[i].extension,
          });
          innerProjectObj[innerKey].items = newItems;
        } else {
          innerProjectObj[innerKey] = {
            folderid: f.folder.folderid,
            foldername: f.folder.foldername,
            clientid: f.folder.clientid,
            foldertype: f.folder.foldertype,
            // innerfoldertype: f.folder.innerfoldertype,
            items: [
              {
                filename,
                sourcefilename,
                // filetype: 1,
                folderid: f.folder.folderid,
                uploadfileid: res[i].fileid,
                extension: res[i].extension,
              },
            ],
          };
        }
      } else if (type === '2') {
        // 上传到任务
        const key = f.task.recid;
        if (toTaskObj[key]) {
          const newFiles = toTaskObj[key].files;
          newFiles.push({
            filename,
            sourcefilename,
            uploadfileid: res[i].fileid,
          });
          toTaskObj[key].files = newFiles;
        } else {
          toTaskObj[key] = {
            taskid: key,
            files: [
              {
                filename,
                sourcefilename,
                uploadfileid: res[i].fileid,
              },
            ],
          };
        }
      }
    });
    // console.log(toProjectObj, innerProjectObj);
    // 遍历对象为数组
    const uploadProjectData = [];
    for (let key in toProjectObj) {
      const files = toProjectObj[key].files.map((k) => innerProjectObj[k]);
      uploadProjectData.push(projectServer.saveFile({ ...toProjectObj[key], files }));
    }

    const uploadTaskData = [];
    for (let key in toTaskObj) {
      uploadTaskData.push(taskServer.saveFile(toTaskObj[key]));
    }

    try {
      const allRes = await Promise.all([...uploadProjectData, ...uploadTaskData]);
      message.success('上传成功！！！');
      this.setState({
        files: [],
        loading: false,
        loadText: '',
      });
    } catch (error) {
      message.warning('文件上传失败！');
    }
  };

  render() {
    const { groupname, begintime } = this.props;
    const { showMock, pickerShow, loading, loadText, showModalData } = this.state;
    const { projectid, projecttype, stages } = this.props.projectState.detailData || {};
    const { info } = this.props.taskState.detailData || {};
    return (
      <>
        {!!loading && (
          <div
            style={{
              position: 'absolute',
              top: 0,
              right: 0,
              bottom: 0,
              left: 0,
              backgroundColor: 'rgba(0,0,0,0.3)',
              zIndex: 4000,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Spin tip={loadText} />
          </div>
        )}
        <div className={this.props.style} style={{ position: 'relative' }} id="DragContent">
          {showMock && (
            <div
              style={{
                position: 'absolute',
                top: 0,
                right: 0,
                bottom: 0,
                left: 0,
                backgroundColor: '#333',
                opacity: 0.3,
                zIndex: 4000,
              }}
            />
          )}
          {this.props.children}
          {
            !info?.recid && <PickerModal
            title={info&&info.recid?("请选择保存路径"+info.recid):"请选择保存路径"}
            showfooter
            type={info?.recid ? '2' : '1'}
            taskid={info?.recid}
            stageid={stages?.length && stages[stages.length - 1]?.stageid ? stages[stages.length - 1]?.stageid : ''}
            projectid={projectid}
            projecttype={projecttype}
            needReflesh={false}
            visible={pickerShow}
            onOk={this.onPathValueChange}
            onCancel={this.hidePickerModal}
          />
          }
          {!!showModalData && (
            <UploadModal
              stagename={showModalData.stagename}
              recname={showModalData.recname}
              folderName={showModalData.folderName}
              groupname={groupname||''}
              begintime={begintime||''}
              show={true}
              key={`DragView`}
              type={projectid ? '1' : '2'}
              showModalData={showModalData}
              onUploadResult={this.onUploadResult}
              onCancel={() => this.setState({ showModalData: null })}
              goBack={()=>this.setState({pickerShow: true, showModalData: false})}
            />
          )}
        </div>
      </>
    );
  }
}

export default DragView;
